/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
$.fn.category = function( options ){
	var _defaults = {name:"category_parent_id", category_id:0};
	var _defaults = jQuery.extend(_defaults,options);
	var obj = this;
	jQuery._xmlData = '';
	this.init = function (){
		$.ajax({
			 type: "GET",
			 url: "/city/xml/",
			 dataType:   "xml",
			 async: false,
			 success: function (xml){
				 jQuery._xmlData = xml;
			 }
		});
		if( $('#'+_defaults.name).html() == null){
			var id = _defaults.category_id > 0 ? _defaults.category_id  : '';
			$(obj).after('<div style="float:left;height:20px;line-height:20px"><input type="hidden" name="'+_defaults.name+'" id="'+_defaults.name+'" value="'+ id +'" /></div>');
		}
		
	};
	this.show = function(){
		if( typeof(jQuery._xmlData) != 'object'){
			this.init();
		}
		if( _defaults.category_id > 0 ){
			var tree = $(jQuery._xmlData).find("root").find("[ id = '"+_defaults.category_id+"' ]").attr("tree").split(',');
			this.select(tree[0], 0 );//this.select(tree[0], 0 );
			var n = 0;//var n = 0;  0,10,1345
			for(i = 1; i < tree.length;i++){
				this.select( tree[i], tree[n] );
				n++;
			}
		}else{
			this.select(0, 0 );
		}
	};
	/**
	 * param id 默认的选中编号
	 * @param parentid 父分类
	 */
	this.select = function (id, parentid){
		if( typeof(jQuery._xmlData) != 'object'){
			this.init();
		}
		if( $(jQuery._xmlData).find("root").find("[ parentid = '"+ parentid +"' ]").size() > 0){
			var select = '<select name="citySelect[]" class="citySelect" >';
			select = select + '<option value="0">请选择</option>';
			$(jQuery._xmlData).find("root").find("[ parentid = '"+ parentid +"' ]").each(function(){
				if( $(this).attr("id") == id){
					select= select + '<option value="'+$(this).attr('id')+'" selected="selected" >'+$(this).attr('name')+'</option>';
				}else{
					select= select + '<option value="'+$(this).attr('id')+'">'+$(this).attr('name')+'</option>';
				}
			});
			select = select + '</select>';
			$(obj).append(select);
			$(obj).find("select").unbind();
			$(obj).find("select").bind("change", function(){
				$(this).nextAll().remove();
				if($(this).val()!=0){
					obj.select(0,$(this).val());					
				}
				return false;
			});
		}else{
			$('#'+_defaults.name).val( parentid );
		}
	};
	return this;
};